<template>
  <view>
    <!-- 固定在顶部的导航栏 -->
    <view class="xen-navbar" :style="containerStyle">
      <!-- 导航栏内容区 -->
      <view class="xen-navbar__content" :style="navbarContentStyle">
        <!-- 左侧区域 -->
        <view class="xen-navbar__left" :style="leftSlotStyle">
          <slot name="left">
            <view
              v-if="showBack"
              class="xen-navbar__back-btn"
              @click="handleBack"
            >
              <uni-icons
                type="left"
                size="24"
                :color="navbarIconColor"
              ></uni-icons>
              <text v-if="backText" class="xen-navbar__back-text">{{
                backText
              }}</text>
            </view>
          </slot>
        </view>

        <!-- 中间标题区域 -->
        <view class="xen-navbar__center" :style="centerStyle">
          <slot name="center">
            <view class="xen-navbar__title-container">
              <text class="xen-navbar__title" :style="titleTextStyle"
                >{{ title }}
              </text>
            </view>
          </slot>
        </view>

        <!-- 右侧区域 -->
        <view class="xen-navbar__right" :style="rightStyle">
          <slot name="right"></slot>
        </view>
      </view>
    </view>

    <!-- 当导航栏固定时，创建一个占位空间 -->
    <view
      v-if="fixed && !noPlaceholder"
      class="xen-navbar-placeholder"
      :style="{ height: `${totalNavbarHeight}px` }"
    ></view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";

// 定义props
const props = defineProps({
  // 标题
  title: {
    type: String,
    default: "",
  },
  // 标题样式
  titleStyle: {
    type: Object,
    default: () => ({}),
  },
  // 标题对齐方式：left, center, right
  titleAlign: {
    type: String,
    default: "center",
    validator: (value: string) => ["left", "center", "right"].includes(value),
  },
  // 是否显示返回按钮
  showBack: {
    type: Boolean,
    default: true,
  },
  // 返回按钮文字
  backText: {
    type: String,
    default: "",
  },
  // 返回按钮图标颜色
  navbarIconColor: {
    type: String,
    default: "#000000",
  },
  // 导航栏背景色
  backgroundColor: {
    type: String,
    default: "#FFFFFF",
  },
  // 导航栏文字颜色
  color: {
    type: String,
    default: "#000000",
  },
  // 导航栏高度（不包括安全区域）
  height: {
    type: Number,
    default: 44,
  },
  // 是否固定在顶部
  fixed: {
    type: Boolean,
    default: true,
  },
  // 是否显示底部边框
  border: {
    type: Boolean,
    default: false,
  },
  // 是否开启顶部安全区域适配
  safeAreaInsetTop: {
    type: Boolean,
    default: true,
  },
  // 是否不需要占位符（某些特殊场景下可能不需要占位）
  noPlaceholder: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["back", "height-change"]);

// 系统信息
const safeAreaInsets = ref<any>({});
const menuButtonInfo = ref<any>({});
const windowInfo = ref<any>({});
const hasMenuButton = ref(false);
const totalNavbarHeight = ref(0); // 导航栏总高度

// 获取系统信息和胶囊按钮位置
onMounted(() => {
  // 获取系统信息，包括安全区域
  const systemInfo = uni.getSystemInfoSync();
  safeAreaInsets.value = systemInfo.safeAreaInsets || {
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
  };
  windowInfo.value = systemInfo;

  // #ifdef MP-WEIXIN
  // 获取微信小程序胶囊按钮信息
  try {
    const menuButton = uni.getMenuButtonBoundingClientRect();
    if (menuButton) {
      menuButtonInfo.value = menuButton;
      hasMenuButton.value = true;
    }
  } catch (e) {
    // 静默处理错误
  }
  // #endif

  // 计算导航栏总高度并通知父组件
  updateNavbarHeight();
});

// 监听高度变化
watch([() => props.height, () => props.safeAreaInsetTop], () => {
  updateNavbarHeight();
});

// 更新导航栏高度
const updateNavbarHeight = () => {
  // #ifdef MP-WEIXIN
  if (
    hasMenuButton.value &&
    menuButtonInfo.value.top &&
    menuButtonInfo.value.height
  ) {
    // 微信小程序：胶囊按钮的top + 胶囊按钮的height + 4px额外间距
    totalNavbarHeight.value =
      menuButtonInfo.value.top + menuButtonInfo.value.height + 4;
  } else {
    const safeAreaTop = props.safeAreaInsetTop
      ? safeAreaInsets.value?.top || 0
      : 0;
    totalNavbarHeight.value = safeAreaTop + props.height + 4;
  }
  // #endif

  // #ifndef MP-WEIXIN
  const safeAreaTop = props.safeAreaInsetTop
    ? safeAreaInsets.value?.top || 0
    : 0;
  totalNavbarHeight.value = safeAreaTop + props.height + 4;
  // #endif

  // 通知父组件高度变化
  emit("height-change", totalNavbarHeight.value);
};

// 计算容器样式
const containerStyle = computed(() => {
  const style: any = {
    color: props.color,
  };

  // 处理背景色，支持渐变
  if (props.backgroundColor.includes("gradient")) {
    style.background = props.backgroundColor;
  } else {
    style.backgroundColor = props.backgroundColor;
  }

  // 添加安全区域适配
  if (props.safeAreaInsetTop) {
    // #ifdef MP-WEIXIN
    if (hasMenuButton.value && menuButtonInfo.value.top) {
      // 微信小程序：使用胶囊按钮的top值 + 4px额外间距
      style.paddingTop = menuButtonInfo.value.top + 4 + "px";
    } else {
      style.paddingTop = (safeAreaInsets.value?.top || 0) + 4 + "px";
    }
    // #endif

    // #ifndef MP-WEIXIN
    style.paddingTop = (safeAreaInsets.value?.top || 0) + 4 + "px";
    // #endif
  } else {
    // 即使不开启安全区域适配，也加4px间距
    style.paddingTop = "4px";
  }

  if (props.fixed) {
    style.position = "fixed";
    style.top = 0;
    style.left = 0;
    style.right = 0;
    style.zIndex = 100;
  }

  if (props.border) {
    style.borderBottom = "1px solid #eeeeee";
  }

  return style;
});

// 计算内容样式
const navbarContentStyle = computed(() => {
  const style: any = {
    height: `${props.height}px`,
  };

  // #ifdef MP-WEIXIN
  if (hasMenuButton.value && menuButtonInfo.value.height) {
    // 微信小程序：使用胶囊按钮的高度
    style.height = `${menuButtonInfo.value.height}px`;
  }
  // #endif

  return style;
});

// 计算左侧插槽样式
const leftSlotStyle = computed(() => {
  const style: any = {};

  // 如果标题左对齐且没有返回按钮
  if (props.titleAlign === "left" && !props.showBack) {
    style.flex = "0 0 auto";
    style.minWidth = "0";
  }

  return style;
});

// 计算中间区域样式
const centerStyle = computed(() => {
  const style: any = {};

  // 根据标题对齐方式调整
  if (props.titleAlign === "left") {
    style.justifyContent = "flex-start";

    // 如果没有左侧内容且标题左对齐
    if (!props.showBack) {
      style.paddingLeft = "10px";
    }
  } else if (props.titleAlign === "right") {
    style.justifyContent = "flex-end";
  } else {
    style.justifyContent = "center";
  }

  // #ifdef MP-WEIXIN
  // 微信小程序胶囊按钮适配
  if (
    hasMenuButton.value &&
    menuButtonInfo.value.width &&
    props.titleAlign === "center"
  ) {
    // 计算标题区域最大宽度，避免被胶囊按钮遮挡
    const menuLeft = menuButtonInfo.value.left || 0;
    const offsetRight = windowInfo.value.windowWidth - menuLeft;

    // 保持标题两侧距离对称
    style.paddingRight = `${offsetRight}px`;
    style.paddingLeft = `${offsetRight}px`;
  }
  // #endif

  return style;
});

// 计算右侧区域样式
const rightStyle = computed(() => {
  const style: any = {};

  // #ifdef MP-WEIXIN
  if (hasMenuButton.value) {
    style.marginRight = `${menuButtonInfo.value.width + 10}px`;
  }
  // #endif

  // 如果标题右对齐
  if (props.titleAlign === "right") {
    style.flex = "0 0 auto";
    style.minWidth = "0";
  }

  return style;
});

// 计算标题文本样式
const titleTextStyle = computed(() => {
  return {
    color: props.color,
    ...props.titleStyle,
  };
});

// 返回上一页
const handleBack = () => {
  emit("back");
  uni.navigateBack({
    delta: 1,
    fail: () => {
      // 如果无法返回上一页，则回到首页
      uni.switchTab({
        url: "/pages/work/work",
        fail: () => {
          // 静默处理错误
        },
      });
    },
  });
};
</script>

<style lang="scss" scoped>
.xen-navbar {
  width: 100%;
  box-sizing: border-box;
  margin: 0;
  padding: 0;

  &__content {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    position: relative;
    margin: 0;
    padding: 0;
  }

  &__left {
    display: flex;
    align-items: center;
    padding-left: 10px;
    min-width: 60px;
    height: 100%;
    margin: 0;
  }

  &__center {
    flex: 1;
    display: flex;
    align-items: center;
    height: 100%;
    overflow: hidden;
    margin: 0;
    padding: 0;
  }

  &__right {
    display: flex;
    align-items: center;
    padding-right: 10px;
    min-width: 60px;
    height: 100%;
    justify-content: flex-end;
    margin: 0;
  }

  &__title {
    font-size: 16px;
    font-weight: 500;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 100%;
    margin: 0;
    padding: 0;
  }

  &__back-btn {
    display: flex;
    align-items: center;
    height: 100%;
    padding: 0 5px;
    margin: 0;
  }

  &__back-text {
    font-size: 14px;
    margin: 0 0 0 2px;
    padding: 0;
  }
}

/* 占位元素，用于固定导航栏时，内容不被遮挡 */
.xen-navbar-placeholder {
  width: 100%;
  margin: 0;
  padding: 0;
}
</style>
